﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO.Ports;

namespace WpfApp1
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

        }
        TcpListener server;
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Task.Run(() => Run());
        }
        void Run()
        {
            try
            {
                var port = this.Dispatcher.Invoke<int>(new Func<int>(() => {
                    return int.Parse(txtPort.Text.Trim());
                }));
                server = new TcpListener(port);
                server.Start();
                Console.WriteLine("服务已启动:{0}", port);
                while (true)
                {
                    TcpClient client = server.AcceptTcpClient();//接受一个Client  
                    Task.Run(() => AcceptTcpClient(client));
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }

        }

        void AcceptTcpClient(TcpClient client)
        {
            try
            {
                while (true)
                {
                    var context = this.Dispatcher.Invoke<string>(new Func<string>(() => {
                        return txtContext.Text.Trim();
                    }));
                    var msg = Encoding.Default.GetBytes(context + " \r\n");
                    NetworkStream stream = client.GetStream();//获取网络流  
                    stream.Write(msg, 0, msg.Length);

                    Console.WriteLine("发送内容:{0}", context);
                    Thread.Sleep(50);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }

    }
}

